package com.summer.log.web.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class WebLogHandler {

    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("execution(public * com.summer.log..*.*(..))")
    public void log() {

    }

    @Before("log()")
    public void beforeLog(JoinPoint jp) throws Throwable {
        startTime.set(System.currentTimeMillis());
        // 日志记录
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("请求地址：{}, 请求参数：{}, 请求方法：{}", (request.getRemoteHost() + request.getRemotePort()), Arrays.toString(jp.getArgs()), jp.getSignature().getDeclaringTypeName() + "." + jp.getSignature().getName());
    }

    @AfterReturning(returning = "res", pointcut = "log()")
    public void returningLog(Object res) throws Throwable {
        // 记录一下日志
        long exeTime = System.currentTimeMillis() - startTime.get();

        log.info("请求耗时：{}", exeTime);
    }

}
